import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useLibraryStore = defineStore('library', () => {
  // 素材分类
  const categories = ref([
    {
      id: 'furniture',
      name: '家具',
      icon: 'sofa',
      description: '各种家具和装饰品',
      items: []
    },
    {
      id: 'appliances',
      name: '电器',
      icon: 'tv',
      description: '家用电器和电子设备',
      items: []
    },
    {
      id: 'lighting',
      name: '照明',
      icon: 'lightbulb',
      description: '灯具和照明设备',
      items: []
    },
    {
      id: 'bathroom',
      name: '卫浴',
      icon: 'bath',
      description: '卫生间和浴室用品',
      items: []
    },
    {
      id: 'kitchen',
      name: '厨房',
      icon: 'utensils',
      description: '厨房用品和厨具',
      items: []
    },
    {
      id: 'doors',
      name: '门窗',
      icon: 'door-open',
      description: '门、窗和隔断',
      items: []
    },
    {
      id: 'decorations',
      name: '装饰',
      icon: 'paint-brush',
      description: '装饰品和艺术品',
      items: []
    },
    {
      id: 'plants',
      name: '植物',
      icon: 'seedling',
      description: '室内植物和花卉',
      items: []
    }
  ])

  // 当前选中的分类
  const selectedCategory = ref('furniture')

  // 搜索状态
  const searchQuery = ref('')
  const searchResults = ref([])
  const isSearching = ref(false)

  // 收藏夹
  const favorites = ref([])

  // 最近使用
  const recentItems = ref([])

  // 计算属性
  const currentCategory = computed(() => 
    categories.value.find(cat => cat.id === selectedCategory.value)
  )

  const currentCategoryItems = computed(() => 
    currentCategory.value ? currentCategory.value.items : []
  )

  const filteredItems = computed(() => {
    if (searchQuery.value.trim()) {
      return searchResults.value
    }
    return currentCategoryItems.value
  })

  const favoriteItems = computed(() => {
    return favorites.value.map(favId => {
      for (const category of categories.value) {
        const item = category.items.find(item => item.id === favId)
        if (item) return item
      }
      return null
    }).filter(Boolean)
  })

  const totalItems = computed(() => 
    categories.value.reduce((total, cat) => total + cat.items.length, 0)
  )

  // Actions
  const setSelectedCategory = (categoryId) => {
    selectedCategory.value = categoryId
    searchQuery.value = ''
    searchResults.value = []
  }

  const selectItem = (item) => {
    // 添加到最近使用
    addToRecent(item)
    
    // 这里可以触发事件通知其他组件
  }

  const searchItems = async (query) => {
    searchQuery.value = query
    isSearching.value = true
    
    try {
      if (query.trim()) {
        // 在所有分类中搜索
        const results = []
        for (const category of categories.value) {
          const categoryResults = category.items.filter(item => 
            item.name.toLowerCase().includes(query.toLowerCase()) ||
            item.tags.some(tag => tag.toLowerCase().includes(query.toLowerCase()))
          )
          results.push(...categoryResults)
        }
        searchResults.value = results
      } else {
        searchResults.value = []
      }
    } catch (error) {
      console.error('搜索失败:', error)
      searchResults.value = []
    } finally {
      isSearching.value = false
    }
  }

  const clearSearch = () => {
    searchQuery.value = ''
    searchResults.value = []
    isSearching.value = false
  }

  const addToFavorites = (itemId) => {
    if (!favorites.value.includes(itemId)) {
      favorites.value.push(itemId)
      saveFavorites()
    }
  }

  const removeFromFavorites = (itemId) => {
    const index = favorites.value.indexOf(itemId)
    if (index !== -1) {
      favorites.value.splice(index, 1)
      saveFavorites()
    }
  }

  const toggleFavorite = (itemId) => {
    if (favorites.value.includes(itemId)) {
      removeFromFavorites(itemId)
    } else {
      addToFavorites(itemId)
    }
  }

  const isFavorite = (itemId) => {
    return favorites.value.includes(itemId)
  }

  const addToRecent = (item) => {
    // 移除已存在的项目
    const index = recentItems.value.findIndex(recent => recent.id === item.id)
    if (index !== -1) {
      recentItems.value.splice(index, 1)
    }
    
    // 添加到开头
    recentItems.value.unshift({
      ...item,
      usedAt: Date.now()
    })
    
    // 限制最近使用数量
    if (recentItems.value.length > 20) {
      recentItems.value = recentItems.value.slice(0, 20)
    }
    
    saveRecentItems()
  }

  const clearRecentItems = () => {
    recentItems.value = []
    saveRecentItems()
  }

  const getItemById = (itemId) => {
    for (const category of categories.value) {
      const item = category.items.find(item => item.id === itemId)
      if (item) return item
    }
    return null
  }

  const getItemsByCategory = (categoryId) => {
    const category = categories.value.find(cat => cat.id === categoryId)
    return category ? category.items : []
  }

  const getItemsByTag = (tag) => {
    const results = []
    for (const category of categories.value) {
      const categoryResults = category.items.filter(item => 
        item.tags.includes(tag)
      )
      results.push(...categoryResults)
    }
    return results
  }

  const addItem = (categoryId, item) => {
    const category = categories.value.find(cat => cat.id === categoryId)
    if (category) {
      const newItem = {
        id: generateId(),
        name: '新素材',
        description: '',
        tags: [],
        thumbnail: null,
        model: null,
        dimensions: { width: 100, height: 100, depth: 100 },
        price: 0,
        manufacturer: '',
        createdAt: Date.now(),
        ...item
      }
      
      category.items.push(newItem)
      return newItem
    }
  }

  const updateItem = (itemId, updates) => {
    for (const category of categories.value) {
      const itemIndex = category.items.findIndex(item => item.id === itemId)
      if (itemIndex !== -1) {
        category.items[itemIndex] = { ...category.items[itemIndex], ...updates }
        return category.items[itemIndex]
      }
    }
  }

  const deleteItem = (itemId) => {
    for (const category of categories.value) {
      const itemIndex = category.items.findIndex(item => item.id === itemId)
      if (itemIndex !== -1) {
        category.items.splice(itemIndex, 1)
        
        // 从收藏夹中移除
        removeFromFavorites(itemId)
        
        // 从最近使用中移除
        const recentIndex = recentItems.value.findIndex(item => item.id === itemId)
        if (recentIndex !== -1) {
          recentItems.value.splice(recentIndex, 1)
          saveRecentItems()
        }
        
        return true
      }
    }
    return false
  }

  /**
   * 从 src/assets/img 下各分类文件夹自动加载图片作为素材项
   * 目录结构示例：
   * - src/assets/img/furniture/*.png
   * - src/assets/img/appliances/*.jpg
   */
  const loadAssetsFromFolders = () => {
    // 先清空现有 items，避免重复累积
    categories.value.forEach(cat => { cat.items = [] })

    // 支持的图片扩展名
    const modules = import.meta.glob('/src/assets/img/*/*.{png,jpg,jpeg,webp,svg}', {
      eager: true,
      as: 'url'
    })
    
    
    // 路径解析与入库
    Object.entries(modules).forEach(([path, url]) => {
      // path 形如：/src/assets/img/furniture/sofa-1.png
      const segments = path.split('/')
      const folder = segments[segments.length - 2] // 分类文件夹名
      const file = segments[segments.length - 1]
      const dotIndex = file.lastIndexOf('.')
      const nameBase = dotIndex > 0 ? file.substring(0, dotIndex) : file

      // 在已存在分类中查找匹配的 id（与文件夹名一致）
      const category = categories.value.find(cat => cat.id === folder)
      if (!category) return

      const newItem = {
        id: generateId(),
        name: nameBase,
        description: '',
        tags: [],
        thumbnail: url,
        model: null,
        dimensions: { width: 0, height: 0, depth: 0 },
        price: 0,
        manufacturer: '',
        createdAt: Date.now(),
        categoryId: category.id,
        sourcePath: path
      }

      category.items.push(newItem)
    })
  }

  const duplicateItem = (itemId) => {
    const originalItem = getItemById(itemId)
    if (originalItem) {
      const duplicatedItem = {
        ...originalItem,
        id: generateId(),
        name: `${originalItem.name} 副本`,
        createdAt: Date.now()
      }
      
      // 添加到原分类
      const category = categories.value.find(cat => cat.id === originalItem.categoryId)
      if (category) {
        category.items.push(duplicatedItem)
        return duplicatedItem
      }
    }
  }

  const importItems = async (file) => {
    try {
      const text = await file.text()
      const data = JSON.parse(text)
      
      if (data.items && Array.isArray(data.items)) {
        data.items.forEach(item => {
          const category = categories.value.find(cat => cat.id === item.categoryId)
          if (category) {
            category.items.push({
              ...item,
              id: generateId(),
              createdAt: Date.now()
            })
          }
        })
        
        return { success: true, count: data.items.length }
      }
    } catch (error) {
      console.error('导入失败:', error)
      return { success: false, error: error.message }
    }
  }

  const exportItems = (categoryId = null) => {
    const items = categoryId 
      ? getItemsByCategory(categoryId)
      : categories.value.flatMap(cat => cat.items)
    
    const exportData = {
      version: '1.0',
      exportTime: Date.now(),
      items: items.map(item => ({
        ...item,
        categoryId: categoryId || item.categoryId
      }))
    }
    
    return exportData
  }

  const loadSampleData = () => {
    // 默认从 assets 目录加载
    loadAssetsFromFolders()
  }

  const saveFavorites = () => {
    localStorage.setItem('designer-favorites', JSON.stringify(favorites.value))
  }

  const loadFavorites = () => {
    const saved = localStorage.getItem('designer-favorites')
    if (saved) {
      try {
        favorites.value = JSON.parse(saved)
      } catch (error) {
        console.error('加载收藏夹失败:', error)
      }
    }
  }

  const saveRecentItems = () => {
    localStorage.setItem('designer-recent-items', JSON.stringify(recentItems.value))
  }

  const loadRecentItems = () => {
    const saved = localStorage.getItem('designer-recent-items')
    if (saved) {
      try {
        recentItems.value = JSON.parse(saved)
      } catch (error) {
        console.error('加载最近使用失败:', error)
      }
    }
  }

  const reset = () => {
    categories.value.forEach(category => {
      category.items = []
    })
    selectedCategory.value = 'furniture'
    searchQuery.value = ''
    searchResults.value = []
    favorites.value = []
    recentItems.value = []
  }

  // 辅助函数
  const generateId = () => {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  // 初始化
  const initialize = () => {
    loadFavorites()
    loadRecentItems()
    loadAssetsFromFolders()
  }
  initialize()
  return {
    // 状态
    categories,
    selectedCategory,
    searchQuery,
    searchResults,
    isSearching,
    favorites,
    recentItems,
    
    // 计算属性
    currentCategory,
    currentCategoryItems,
    filteredItems,
    favoriteItems,
    totalItems,
    
    // Actions
    setSelectedCategory,
    selectItem,
    searchItems,
    clearSearch,
    addToFavorites,
    removeFromFavorites,
    toggleFavorite,
    isFavorite,
    addToRecent,
    clearRecentItems,
    getItemById,
    getItemsByCategory,
    getItemsByTag,
    addItem,
    updateItem,
    deleteItem,
    duplicateItem,
    importItems,
    exportItems,
    loadSampleData,
    loadAssetsFromFolders,
    saveFavorites,
    loadFavorites,
    saveRecentItems,
    loadRecentItems,
    reset,
    initialize
  }
})
